<template lang="html">
  <el-drawer v-model="drawer" direction="ltr" size="40%" :before-close="handleClose">
    <div class="book-scroll" id="drawer-book-chapter">
      <div class="drawer-book-chapter-volume" v-for="(group, key) in groupChapters">
        <div class="drawer-book-chapter-title" :key="key">
          {{ key }}
        </div>
        <div class="drawer-book-chapter-list">
          <div class="drawer-book-chapter-item" v-for="item in group" :key="item.id" :title="item.name"
            :class="{ 'is-active': item.id == currentChapter.id }" @click="chapterClick(item)">
            {{ item.name }}
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, watch, inject, nextTick } from 'vue';
import _ from 'lodash';

const bookContentEvent = inject('bookContentEvent'); // 获取父组件的事件

const props = defineProps({
  bookChapters: {
    type: Array,
    default: () => [],
  },
  currentChapter: {
    type: Object,
    default: () => { },
  },
});

const groupChapters = ref({});

watch(() => props.bookChapters, (newValue, oldValue) => {
  groupChapters.value = _.groupBy(newValue, (item) => {
    return item.volumeName;
  });

  console.log('groupChapters', groupChapters.value);
})

const drawer = ref(false);

function openDrawer() {
  drawer.value = true;

  nextTick(() => {
    const bookContent = document.getElementById('drawer-book-chapter');

    const activeElement = bookContent.querySelector('.is-active');
    activeElement.scrollIntoView({ block: "start", behavior: "smooth" });
  });
}


function chapterClick(item) {
  bookContentEvent.choseChapter(item);
  drawer.value = false;
}

defineExpose({
  openDrawer,
});

</script>
<style lang="less" scoped>
#drawer-book-chapter {
  height: 100%;
  overflow: hidden;
  overflow-y: scroll;

  .drawer-book-chapter-volume {
    margin-bottom: 10px;

    .drawer-book-chapter-title {
      font-size: 22px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .drawer-book-chapter-list {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;

      .drawer-book-chapter-item {
        flex: 1 1 250px;
        padding: 5px;
        border-radius: 4px;
        cursor: pointer;
        border-bottom: 1px solid #eaeaea;
        height: 30px;
        line-height: 30px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        &:hover {
          background-color: #f0f0f0;
        }

        &.is-active {
          color: #e5353e;
        }
      }
    }
  }
}
</style>
